package com.apes.fn.business.insurance.modle;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.util.*;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName : PolicyInformation
 * @Description : 保单信息
 * @Author : WSJ
 * @Date: 2020-04-28 14:16
 */
@Getter
@Setter
@Entity
@Table(name = PolicyInformation.CONST_TABLE_NAME)
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@EntityListeners(DefaultPersistListener.class)
public class PolicyInformation extends BaseModel {
    public static final String CONST_TABLE_NAME = "policy_information";
    public static final String CONST_SOURCE_FORM_APP = "AppOrder";
    public static final String CONST_SOURCE_FORM_FIX = "InsurancePolicyFix";

    @Id
    @Column(name = "id", nullable = false, length = 32)
    @Comment("保单号")
    private  String id;

    @Column(name = "plate_License", nullable = false, length = 32)
    @Comment("车牌号码")
    private String plateLicense;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "issue_Date")
    @Comment("出单日期")
    private Date issueDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "start_Date")
    @Comment("起保时间")
    private Date startDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "end_Date")
    @Comment("终保时间")
    private Date endDate;

    @Comment("收款日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "receipt_date")
    private Date receiptDate;

    @Comment("报价日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "quote_Date")
    private Date quoteDate;

    @Column(name = "city", length = 32)
    @Comment("城市名称")
    private String city;

    @Column(name = "province", length = 32)
    @Comment("省份")
    private String province;

    @Column(name = "use", length = 32)
    @Comment("使用性质(1:营运;2:非营运)")
    private String use;

    @Column(name = "Type", length = 32)
    @Comment("保险类型(缺省0,新保1,断保2,续保3)")
    private String type;

    @Column(name = "insurance_Type", length = 32)
    @Comment("险种类别(0:商业险,1：交强险,2:驾意险)")
    private String insuranceType;

    @Comment("保险金额")
    @Column(name = "insurance_amount",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private Double insuranceAmount;

    @Comment("第三责任险金额")
    @Column(name = "item_Third_Price",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private Double itemThirdPrice;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier;

    @Comment("净保费")
    @Column(name = "net_Premium",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private Double netPremium;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("门店")
    private Dept dept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "salesman_id", referencedColumnName = "id")
    @Comment("业务员")
    private PartyRole salesman;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("所属公司")
    private PartyRole company;

    @Column(name = "belong_plan", length = 32)
    @Comment("方案所属")
    private String belongPlan;

    @Column(name = "external_staff", length = 32)
    @Comment("外部业务员")
    private String externalStaff;

    @Column(name = "vin", length = 64)
    @Comment("车架号")
    private String vin;

    @Column(name = "engine_model",length = 120)
    @Comment("发动机型号")
    private String engineModel;

    @Column(name = "car_Ownership",length = 64)
    @Comment("车辆所有权(1个人，2企业)")
    private String carOwnership;

    @Comment("新车价格")
    @Column(name = "car_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private Double carPrice;

    @Comment("车船税")
    @Column(name = "car_Ship_Tax", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private Double carShipTax;

    @Comment("赋能常规提成比率")
    @Column(name = "fn_Profit_Ratio",nullable = false, columnDefinition = ApesConst.FIELD_ROUND_16_8)
    private double fnProfitRatio = 0;

    @Comment("赋能常规提成")
    @Column(name = "fn_Profit",nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double fnProfit = 0 ;

    @Column(name = "discount_Type", length = 32)
    @Comment("优惠类型")
    private String discountType;

    @Column(name = "discount_Type_Name", length = 32)
    @Comment("优惠类型描述")
    private String discountTypeName;


    @Column(name = "total_Percent",  columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("提成比例合计")
    private Double totalPercent;

    @Column(name = "commission_Total_Amount",  columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("提成金额合计")
    private Double commissionTotalAmount;

    @Column(name = "allowance_Percent",  columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("奖励提成比例")
    private Double allowancePercent;

    @Column(name = "allowance_Amount",  columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("奖励提成金额")
    private Double allowanceAmount;

    @Column(name = "APP_Order", length = 32)
    @Comment("APP订单")
    private String APPOrder;


    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType = "AppOrder";//1:AppOrder 2:InsurancePolicyFix

    @Column(name = "transfer_ownership", length = 32)
    @Comment("是否过户车（1：是，0：否）")
    private String transferOwnership;

    @Column(name = "check_and_ratify ", length = 32)
    @Comment("核定载货数")
    private String checkAndRatify;

    @Column(name = "energy", length = 32)
    @Comment("能源类型(0：燃油，1：纯电动，2：燃料电池，3：插电式混合动力，4：其他混合动力)")
    private String energy;

    @Column(name = "grade", length = 32)
    @Comment("保险公司评分")
    private String grade;

    @Column(name = "renew_insurance", length = 32)
    @Comment("是否续保（1：是，0：否）")
    private String renewInsurance;

    @OneToMany(mappedBy = "policyInformation", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<PolicyInformationItem> policyInformationItems = new HashSet();

    public Set<PolicyInformationItem> getPolicyInformationItems() {
        for (PolicyInformationItem item : policyInformationItems) {
            item.setPolicyInformation(this);
        }
        return policyInformationItems;
    }

    /**
     * 平台公司
     **/
    @Transient
    private PartyRole platformCompany;

    public PartyRole getPlatformCompany() {
        if (platformCompany != null) return platformCompany;
        String topic = "event:fn.contract.findFirstValidFnContractCompanyByPartnerId";
        if (getCompany() == null) return null;
        String platformCompanyId = (String) EventUtil.sendSynEvent(this, topic, MapUtil.mapper("partnerId", getCompany().getId())).stream().findFirst().get();
        if (!StringUtils.isEmpty(platformCompanyId)) {
            platformCompany = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findOne(platformCompanyId, "Company"));
            platformCompany = MapUtil.getO(MapUtil.mapped(platformCompany), PartyRole.class);
        }
        return platformCompany;
    }

    /**
     * 1003公司
     **/
    @Transient
    private PartyRole theCompany;

    public PartyRole getTheCompany() {
        if (theCompany != null) return theCompany;
        theCompany = (PartyRole) JpaUtil.getImplementation(SpringManager.getBean(PartyRoleService.class).findOne("1003", "Company"));
        theCompany = MapUtil.getO(MapUtil.mapped(theCompany), PartyRole.class);
        return theCompany;
    }
}
